package org.springblade.auth.config;

import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springblade.auth.converter.CsjJwtAccessTokenConverter;
import org.springblade.auth.granter.WeChatLoginTokenGranter;
import org.springblade.common.constant.SecurityConstants;
import org.springblade.common.security.component.CsjWebResponseExceptionTranslator;
import org.springblade.common.security.service.CsjUser;
import org.springblade.core.launch.constant.TokenConstant;
import org.springblade.core.tool.utils.Charsets;
import org.springblade.core.tool.utils.Func;
import org.springblade.system.user.feign.IUserClient;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.CompositeTokenGranter;
import org.springframework.security.oauth2.provider.TokenGranter;
import org.springframework.security.oauth2.provider.TokenRequest;
import org.springframework.security.oauth2.provider.client.ClientCredentialsTokenGranter;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeTokenGranter;
import org.springframework.security.oauth2.provider.implicit.ImplicitTokenGranter;
import org.springframework.security.oauth2.provider.password.ResourceOwnerPasswordTokenGranter;
import org.springframework.security.oauth2.provider.refresh.RefreshTokenGranter;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.UserAuthenticationConverter;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import java.util.*;

/**
 * @File: AuthorizationServerConfig.java
 * @Project: csjbot-service
 * @Package: org.springblade.auth.config
 * @Description:
 * @Company: 苏州穿山甲机器人股份有限公司
 * @author: zhouhong
 * @date: 2019年11月21 09时59分
 * @version: V1.0.0
 */
@Configuration
@AllArgsConstructor
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
	private final ClientDetailsService clientDetailsService;
	private final UserDetailsService userDetailsService;
	private final AuthenticationManager authenticationManager;
	private final IUserClient userClient;
	private final CacheManager cacheManager;

	@Override
	@SneakyThrows
	public void configure(ClientDetailsServiceConfigurer clients) {
		clients.withClientDetails(clientDetailsService);
	}


	@Override
	public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
		oauthServer
			.allowFormAuthenticationForClients()
			.checkTokenAccess("permitAll()");
	}

	@Override
	public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
		// 自定义token生成方式
		TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
		tokenEnhancerChain.setTokenEnhancers(Arrays.asList(tokenEnhancer(), jwtAccessTokenConverter()));
		endpoints
			.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST)
//			.tokenStore(tokenStore())
			.tokenGranter(tokenGranter(endpoints))
			.tokenEnhancer(tokenEnhancerChain)
			.userDetailsService(userDetailsService)
			.authenticationManager(authenticationManager)
			.reuseRefreshTokens(false)
			.accessTokenConverter(jwtAccessTokenConverter())
			.exceptionTranslator(new CsjWebResponseExceptionTranslator());


	}

	/**
	 *
	 * @param endpoints
	 * @return
	 */
	private WeChatLoginTokenGranter weChatLoginTokenGranter(AuthorizationServerEndpointsConfigurer endpoints){
		return new WeChatLoginTokenGranter(endpoints.getTokenServices(), endpoints.getClientDetailsService(), endpoints.getOAuth2RequestFactory(),userClient,cacheManager);
	}

//	@Bean
//	public TokenStore tokenStore() {
//		RedisTokenStore tokenStore = new RedisTokenStore(redisConnectionFactory);
//		tokenStore.setPrefix(SecurityConstants.PROJECT_PREFIX + SecurityConstants.OAUTH_PREFIX);
//		return tokenStore;
//	}

	/**
	 * 自定义tokenGranter 增加手机app第三方登陆token获取
	 * @param endpoints
	 * @return
	 */
	private TokenGranter tokenGranter(AuthorizationServerEndpointsConfigurer endpoints){
		TokenGranter tokenGranter = new TokenGranter() {
			private CompositeTokenGranter delegate;
			@Override
			public OAuth2AccessToken grant(String grantType, TokenRequest tokenRequest) {
				if(Func.isEmpty(delegate)){
					delegate = new CompositeTokenGranter(getDefaultTokenGranters(endpoints));
				}
				return delegate.grant(grantType,tokenRequest);
			}
		};
		return tokenGranter;
	}

	/**
	 * 从组tokenGranter，增加手机第三方登陆验证方式
	 * @param endpoints
	 * @return
	 */
	private List<TokenGranter> getDefaultTokenGranters(AuthorizationServerEndpointsConfigurer endpoints) {
		List<TokenGranter> tokenGranters = new ArrayList<>();
		//添加授权码验证方式
		tokenGranters.add(new AuthorizationCodeTokenGranter(endpoints.getTokenServices(),
			endpoints.getAuthorizationCodeServices(), endpoints.getClientDetailsService(), endpoints.getOAuth2RequestFactory()));
		//添加验证码刷新方式
		tokenGranters.add(new RefreshTokenGranter(endpoints.getTokenServices(), endpoints.getClientDetailsService(), endpoints.getOAuth2RequestFactory()));
		//添加隐式授权方式
		ImplicitTokenGranter implicit = new ImplicitTokenGranter(endpoints.getTokenServices(), endpoints.getClientDetailsService(),
			endpoints.getOAuth2RequestFactory());
		tokenGranters.add(implicit);
		//添加客户端授权方式
		tokenGranters.add(
			new ClientCredentialsTokenGranter(endpoints.getTokenServices(), endpoints.getClientDetailsService(), endpoints.getOAuth2RequestFactory()));
		if (authenticationManager != null) {
			//添加用户名密码授权方式
			tokenGranters.add(new ResourceOwnerPasswordTokenGranter(authenticationManager,
				endpoints.getTokenServices(), endpoints.getClientDetailsService(), endpoints.getOAuth2RequestFactory()));
		}
		//添加微信授权方式
		tokenGranters.add(weChatLoginTokenGranter(endpoints));
		return tokenGranters;
	}

	/**
	 * 定义token 签名的方式(非对称加密算法来对 Token 进行签名,也可以使用对称加密方式)
	 * @return
	 */
	@Bean
	public JwtAccessTokenConverter jwtAccessTokenConverter() {
		//对称加密方式
		JwtAccessTokenConverter converter = new CsjJwtAccessTokenConverter();
		converter.setSigningKey(Base64.getEncoder().encodeToString(TokenConstant.SIGN_KEY.getBytes(Charsets.UTF_8)));
		return converter;
	}

	@Bean
	public TokenEnhancer tokenEnhancer() {
		return (accessToken, authentication) -> {
			final Map<String, Object> additionalInfo = new HashMap<>(1);
			CsjUser userInfo = (CsjUser) authentication.getUserAuthentication().getPrincipal();
			additionalInfo.put(SecurityConstants.DETAILS_LICENSE, SecurityConstants.PROJECT_LICENSE);
			additionalInfo.put(SecurityConstants.DETAILS_USER_AVATAR, userInfo.getUserInfo().getUser().getAvatar());
			additionalInfo.put(SecurityConstants.DETAILS_USER_ID, userInfo.getUserInfo().getUser().getId());
			additionalInfo.put(SecurityConstants.DETAILS_RPLE_ID, userInfo.getUserInfo().getUser().getRoleId());
			additionalInfo.put(SecurityConstants.DETAILS_USER_ACCOUNT, userInfo.getUserInfo().getUser().getAccount());
			additionalInfo.put(SecurityConstants.DETAILS_USER_NICK_NAME, userInfo.getUserInfo().getUser().getName());
			additionalInfo.put(SecurityConstants.DETAILS_USER_ROLE_NAME, Func.join(userInfo.getUserInfo().getRoles()));
			additionalInfo.put(SecurityConstants.DETAILS_USER_TENANT_ID, userInfo.getUserInfo().getUser().getTenantId());
			additionalInfo.put(UserAuthenticationConverter.AUTHORITIES, Func.join(userInfo.getUserInfo().getPermissions()));
			additionalInfo.put(SecurityConstants.DETAILS_USER_TENANT_ID, userInfo.getUserInfo().getUser().getTenantId());
			additionalInfo.put(SecurityConstants.DETAILS_USER_NAME, userInfo.getUsername());
			((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
			return accessToken;
		};
	}
}
